import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:infinite_scroll_pagination/infinite_scroll_pagination.dart';
import 'package:pornhub_app/components/collection_cell/collection_cell.dart';
import 'package:pornhub_app/components/no_more/no_data.dart';
import 'package:pornhub_app/components/no_more/no_more.dart';
import 'package:pornhub_app/http/http_service.dart';
import 'package:pornhub_app/model/blogger/blogger_video_collection.dart';
import 'package:pornhub_app/utils/events.dart';

class ArroundCompilationPage extends StatefulWidget {
  final int userId;
  const ArroundCompilationPage({super.key, required this.userId});

  @override
  State<ArroundCompilationPage> createState() => _ArroundCompilationPageState();
}

class _ArroundCompilationPageState extends State<ArroundCompilationPage> {
  final _pageSize = 20;
  final PagingController<int, BloggerVideoCollectionModel> _pagingController =
      PagingController(firstPageKey: 1);
  StreamSubscription? subscription;
  @override
  void initState() {
    super.initState();
    _pagingController.addPageRequestListener((pageKey) {
      initListData(pageKey);
    });
    subscription = eventBus.on<BloggerRefreshEvent>().listen((event) {
      if (event.tabName == "合集") {
        _pagingController.refresh();
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return PagedGridView(
      physics: const ClampingScrollPhysics(),
      showNewPageProgressIndicatorAsGridChild: false,
      showNewPageErrorIndicatorAsGridChild: false,
      showNoMoreItemsIndicatorAsGridChild: false,
      padding: EdgeInsets.symmetric(horizontal: 14.w, vertical: 8.w),
      pagingController: _pagingController,
      builderDelegate: PagedChildBuilderDelegate<BloggerVideoCollectionModel>(
          noMoreItemsIndicatorBuilder: (_) {
        return const NoMore();
      }, noItemsFoundIndicatorBuilder: (_) {
        return const NoData();
      }, itemBuilder: (context, value, index) {
        return CollectionCell(
          model: value,
          index: index,
        );
      }),
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          mainAxisSpacing: 14.w,
          crossAxisSpacing: 14.w,
          crossAxisCount: 3,
          childAspectRatio: 114 / 146),
    );
  }

  Future initListData(int pageKey) async {
    final resp = await httpInstance.get<BloggerVideoCollectionModel>(
        url: 'bloggerCollection/queryCollectionByUser',
        queryMap: {
          'userId': widget.userId,
          'page': pageKey,
          'pageSize': _pageSize,
        },
        complete: BloggerVideoCollectionModel.fromJson);

    final isLastPage = resp.length < _pageSize;
    if (isLastPage) {
      _pagingController.appendLastPage(resp);
    } else {
      final nextPageKey = pageKey + 1;
      _pagingController.appendPage(resp, nextPageKey as int?);
    }
  }

  @override
  void dispose() {
    subscription?.cancel();
    super.dispose();
  }
}
